<template>
  <div>
    <div style="display: flex;margin:15px 0 0 35px;min-height:820px;background-color: white;border-radius: 26px">
      <div style="width: 1450px;min-height: 500px;">
        <div style="width: 1360px;height: 44px;padding: 8px 20px;margin:30px 0 0 25px;
    border-radius: 12px;background-color: #F8F8F8;display: flex">
          <div style="width: 80%;margin: auto 20px">
            <p style="margin: 0;">亲爱的 {{user.userName}} 老师，欢迎回来~~</p>
          </div>
<!--          <div style="width: 20%;text-align: right">-->
<!--            <el-button type="primary" style="width: 120px;height: 45px;">继续学习</el-button>-->
<!--          </div>-->
        </div>
        <div style="display: flex;flex-direction: column;">
          <p style="margin:5px 0 0 30px;font-size: 20px;">
            公告
            <el-button class="el-icon-plus" type="primary" @click="onAddAnnounceBut()"
                       style="margin:10px 0 10px 30px">添加公告
            </el-button>
          </p>
          <div v-if="total!==0" style="display: flex;flex-direction: column;">
          <div v-for="(item,index) in announceList" :key="item.announceId" style="margin:10px 30px;border: 2px solid #999999;border-radius: 14px">
            <p style="font-size: 18px;color: #333333;margin-left: 20px">{{item.announceName}}</p>
            <div v-html="item.content" style="margin:0 20px 20px 20px;"></div>
            <p style="float: right;margin-right: 30px">{{item.createTime|formatDate('yyyy-MM-dd HH:mm:ss')}}</p>
            <div style="margin-left: 20px">
              <el-button type="primary" icon="el-icon-edit" :key="'update-'+item.announceId" @click="onUpdateAnnounceBut(item.announceId)" circle></el-button>
              <el-button type="danger" icon="el-icon-delete" :key="'delete-'+item.announceId" @click="onDeleteAnnounceBut(item.announceId)" circle></el-button>
            </div>
          </div>
          <el-pagination
              @size-change="handleSizechange"
              @current-change="getPage"
              :current-page="currentPage"
              :page-sizes="[3,6,10]"
              :page-size="pageSize"
              layout="total,sizes,prev,pager,next,jumper"
              :total="total"
              style="text-align: center">
          </el-pagination>
          </div>
        </div>
      </div>
      <el-dialog
          :visible.sync="announceVisible"
          width="50%"
          top="150px"
          center>
        <el-form v-if="!updateAnnounceFlag" :model="announce" :rules="rules" ref="addAnnounceFrom"
                 style="width: 80%;margin-left: 80px">
          <p style="text-align: center;width: 100%;font-size: 20px">添加公告</p>
          <p style="font-weight: bold;font-size: 16px">公告标题</p>
          <el-form-item prop="announceName">
            <el-input v-model="announce.announceName" placeholder="请输入公告标题"
                      style="width: 350px;height: 46px;margin:10px 0">
            </el-input>
          </el-form-item>
          <p style="font-weight: bold;font-size: 16px">公告内容</p>
          <el-form-item prop="content">
            <div id="div1">
            </div>
          </el-form-item>
          <el-form-item style="text-align: center">
            <el-button type="primary" style="width: 300px" @click="addOrUpdate('addAnnounceFrom')">确 定</el-button>
          </el-form-item>
        </el-form>
        <el-form v-if="updateAnnounceFlag" :model="announce" :rules="rules" ref="updateAnnounceFrom"
                 style="width: 80%;margin-left: 80px">
          <p style="text-align: center;width: 100%;font-size: 20px">编辑公告</p>
          <p style="font-weight: bold;font-size: 16px">公告标题</p>
          <el-form-item prop="announceName">
            <el-input v-model="announce.announceName" placeholder="请输入公告标题"
                      style="width: 350px;height: 46px;margin:10px 0">
            </el-input>
          </el-form-item>
          <p style="font-weight: bold;font-size: 16px">公告内容</p>
          <el-form-item prop="content">
            <div id="div1">
            </div>
          </el-form-item>
          <el-form-item style="text-align: center">
            <el-button type="primary" style="width: 300px" @click="addOrUpdate('updateAnnounceFrom')">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <div style="width: 280px;min-height: 500px;">
        <div style="width: 238px;height: 300px;margin:25px 0 0 10px;background-color: #F7F7F7;border-radius: 12px">
          <p style="padding: 10px;margin:0;font-size: 18px">最近更新</p>
          <p style="padding-left: 10px;margin:0;font-size: 14px">课件</p>
          <p v-for="item in lessonList.slice(0,10)" style="margin: 4px 14px">
            <el-link @click="on_content(courseId,item.chapterId,item.lessonId)" target="_blank">
              {{ item.chapterName }}>{{ item.lessonName }}
            </el-link>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import E from 'wangeditor'
export default{
  name: "AnnounceEditView",
  data(){
    return{
      user:{},
      courseId:'',
      announce:{content: ''},
      announceList:[],
      lessonList: [],
      currentPage: 1,
      pageSize: 3,
      total: 0 ,
      announceVisible:false,
      updateAnnounceFlag:false,
      isChange: false,
      rules: {
        announceName:{required: true, message: '公告标题不能为空', trigger: 'blur'},
        content:{required: true, message: '公告内容不能为空', trigger: 'blur'},
      }
    }
  },
  watch:{
    announce(val){
      if(!this.isChange){
        this.editor.txt.html(this.announce.content);
      }
      this.isChange=false;
    }
  },
  methods:{
    onAddAnnounceBut(){
        this.$nextTick(() => {
          this.$refs.addAnnounceFrom.resetFields();
        });
      this.announce={announce:''};
      this.updateAnnounceFlag=false;
      this.announceVisible=true;
      this.$nextTick(() => {
        if (!this.editor) {
          this.createRichTextEditor();
        }else {
          this.editor.txt.html('');
        }
      });
    },
    onUpdateAnnounceBut(announceId){
      this.updateAnnounceFlag=true;
      this.announceVisible=true;
      this.getAnnounceById(announceId);
      this.$nextTick(() => {
        if (!this.editor) {
          this.createRichTextEditor();
        }else {
          this.editor.txt.html(this.announce.content);
        }
      });
    },
    onDeleteAnnounceBut(announceId){
      this.$confirm('此操作将永久删除该课时, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteAnnounce(announceId);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    getAnnounceById(announceId){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/announce/selectAnnounceById/${announceId}`,
      }).then(res => {
        if(res.data.code===200){
          this.announce = res.data.dataobject;
          this.getPage(this.currentPage);
        }
      }).catch(err => console.log(err));
    },
    getLessonByIdUpdateDesc() {
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/lesson/seleteLessonByCourseIdUpdateTimeDesc/${this.courseId}`,
      }).then(res => {
        if (res.data.code === 200) {
          this.lessonList = res.data.dataobject;
        }
      }).catch(err => console.log(err));
    },
    addAnnouce(){
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/user/announce/createAnnounce",
        data:this.announce
      }).then(res => {
        if(res.data.code===200){
          this.$message.success(res.data.msg);
          this.getPage();
        }else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => console.log(err));
    },
    updateAnnounce(){
      this.$axios({
        method: 'post',
        url: "http://localhost:8089/user/announce/updateAnnounce",
        data:this.announce
      }).then(res => {
        if(res.data.code===200){
          this.$message.success(res.data.msg);
          this.getPage(this.currentPage);
        }else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => console.log(err));
    },
    deleteAnnounce(announceId){
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/user/announce/deleteAnnounce/${announceId}`,
      }).then(res => {
        if(res.data.code===200){
          this.$message.success(res.data.msg);
          this.getPage(this.currentPage);
        }else {
          this.$message.error(res.data.msg);
        }
      }).catch(err => console.log(err));
    },
    //创建富文本编辑器，并进行上传图片、上传视颜的配置
    createRichTextEditor() {
      this.editor = new E('#div1');
      this.editor.config.uploadImgServer = 'http://localhost:8089/richText/uploadFile?type=img';
      this.editor.config.uploadFileName = 'file';
      this.editor.config.uploadVideoServer = 'http://localhost:8089/richText/uploadFile?type=video';
      this.editor.config.uploadVideoName = 'file';
      this.editor.config.placeholder = '请在此处作答';
      this.editor.create();
    },
    //确定按钮
    addOrUpdate(formName) {
      this.announce.content=this.editor.txt.html()
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(formName==='addAnnounceFrom'){
            this.announce.userId=localStorage.getItem('userId');
            this.announce.courseId=this.courseId;
            this.addAnnouce();
          }else {
            this.updateAnnounce();
          }
          this.announceVisible=false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleSizechange(size) {
      this.pageSize = size;
      this.getPage(1);
    },
    getPage(current = 1) {
      this.currentPage = current;
      this.$axios({
        method: 'get',
        url: `http://localhost:8089/announce/getPageByCourseId/${this.currentPage}/${this.pageSize}/${this.courseId}`,
      }).then(res => {
        if(res.data.code===200){
          this.total = res.data.dataobject.total;
          this.announceList = res.data.dataobject.pageList;
        }
      }).catch(err => console.log(err));
    },
    on_content(courseId, chapterId, lessonId) {
      this.$router.push({path: "/learnEdit/contentEdit/" + courseId + "/" + chapterId + "/" + lessonId})
    }
  },
  filters:{
    formatDate: function(value,args) {
      var dt = new Date(value);
      if(args == 'yyyy年MM月dd日') {// yyyy年MM月dd日
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        return `${year}年${month}月${date}日`;
      } else if(args == 'yyyy-MM-dd HH:mm:ss'){// yyyy-MM-dd HH:mm:ss
        let year = dt.getFullYear();
        let month = (dt.getMonth() + 1).toString().padStart(2,'0');
        let date = dt.getDate().toString().padStart(2,'0');
        let hour = dt.getHours().toString().padStart(2,'0');
        let minute = dt.getMinutes().toString().padStart(2,'0');
        let second = dt.getSeconds().toString().padStart(2,'0');
        return `${year}-${month}-${date} ${hour}:${minute}:${second}`;
      }
    }
  },
  created() {
    this.courseId=this.$route.params.courseId;
    this.user['userId']=localStorage.getItem('userId');
    this.user['userName']=localStorage.getItem('userName');
    this.getPage();
    this.getLessonByIdUpdateDesc()
  }
}
</script>

<style scoped>

</style>